package view;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.PassByCache;
import com.passby.Client;
import com.passby.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginView extends Activity {
	private EditText usernameTxt;
	private EditText passwordTxt;
	private Button loginBtn;
	private PassByCache cache;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginview);
        cache = new PassByCache(this);
        findView();
        initListener();
    }
	
	private void findView()
	{
		usernameTxt = (EditText)findViewById(R.id.username);
		passwordTxt = (EditText)findViewById(R.id.password);
		loginBtn = (Button)findViewById(R.id.loginBtn);
	}
	
	private void initListener()
	{
		loginBtn.setOnClickListener(onLoginBtnClick);
	}
	
	private OnClickListener onLoginBtnClick = new OnClickListener() {
		public void onClick(View v) {
			String username = usernameTxt.getText().toString();
			String password = passwordTxt.getText().toString();
			loginBtn.setEnabled(false);
			new LoginTask() { 
		        protected void onPostExecute(Boolean result) {
		            if (result) {
		            	cache.setUser(Client.getInstance().self, Client.accessor.accessToken, Client.accessor.tokenSecret);
		            	Intent intent = new Intent();   
				        intent.setClass(LoginView.this, MainView.class);   
				        startActivity(intent);  
				        finish();
		            }else
		            {
		            	loginBtn.setEnabled(true);
		            }
		        }
		    }.execute(username,password);
		}
	};
	
	private class LoginTask extends AsyncTask<String, Integer, Boolean> {
	    @Override
	    protected Boolean doInBackground(String... arg0) {
	    	Boolean b = false;
			b = Client.getInstance().login(arg0[0], arg0[1]);
	        return b;
	    }	
	}
}
